import os
from PIL import Image
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm

def convert_file(input_path, output_path):
    """Convert a single PNG file to BMP format"""
    try:
        with Image.open(input_path) as img:
            # 保存原始PNG信息
            png_info = {
                'format': img.format,
                'mode': img.mode,
                'size': img.size,
                'info': img.info
            }
            img.save(output_path, 'BMP')
            
            # 获取转换后BMP信息
            with Image.open(output_path) as bmp:
                bmp_info = {
                    'format': bmp.format,
                    'mode': bmp.mode,
                    'size': bmp.size,
                    'info': bmp.info
                }
            
            # 计算文件大小
            png_size = os.path.getsize(input_path)
            bmp_size = os.path.getsize(output_path)
            
            return {
                'success': True,
                'png_info': png_info,
                'bmp_info': bmp_info,
                'png_size': png_size,
                'bmp_size': bmp_size,
                'size_diff': png_size - bmp_size
            }
    except Exception as e:
        return f"Error converting {input_path}: {str(e)}"

def convert_png_to_bmp(input_dirs, max_workers=24):
    """Convert PNG files in multiple directories to BMP format with progress bar"""
    # 去重输入目录
    unique_dirs = list(set(input_dirs))
    
    total_files = 0
    all_png_files = []
    dir_mapping = []
    
    # 收集所有PNG文件并建立目录映射
    for input_dir in unique_dirs:
        # 获取PNG文件
        png_files = [f for f in os.listdir(input_dir) if f.lower().endswith('.png')]
        total_files += len(png_files)
        all_png_files.extend(png_files)
        
        # 创建输出目录路径
        output_dir = os.path.join(os.path.dirname(input_dir), 'BMP_Images')
        os.makedirs(output_dir, exist_ok=True)
        
        # 建立输入输出路径映射
        for filename in png_files:
            input_path = os.path.join(input_dir, filename)
            bmp_filename = os.path.splitext(filename)[0] + '.bmp'
            output_path = os.path.join(output_dir, bmp_filename)
            dir_mapping.append((input_path, output_path))
    
    # 使用线程池并行转换
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        # 使用tqdm显示进度条
        with tqdm(total=total_files, desc="Converting PNG to BMP") as pbar:
            futures = []
            for input_path, output_path in dir_mapping:
                future = executor.submit(convert_file, input_path, output_path)
                future.add_done_callback(lambda _, path=input_path: pbar.update(1))
                futures.append((future, input_path))
            
            # 收集错误信息
            errors = []
            for future, input_path in futures:
                result = future.result()
                if isinstance(result, str) and result.startswith("Error"):
                    errors.append(result)
                elif isinstance(result, dict) and result.get('success'):
                    # 打印转换信息
                    info = (
                        f"文件: {os.path.basename(input_path)}\n"
                        f"PNG格式: {result['png_info']['format']} "
                        f"({result['png_info']['mode']}), "
                        f"大小: {result['png_size']/1024:.2f} KB\n"
                        f"BMP格式: {result['bmp_info']['format']} "
                        f"({result['bmp_info']['mode']}), "
                        f"大小: {result['bmp_size']/1024:.2f} KB\n"
                        f"大小变化: {result['size_diff']/1024:.2f} KB "
                        f"({result['size_diff']/result['png_size']*100:.1f}%)\n"
                    )
                    print(info)
    
    # 输出结果汇总
    output_dirs = set(os.path.dirname(output) for _, output in dir_mapping)
    result_msg = f"转换完成，共处理{total_files}个文件\n"
    result_msg += f"BMP文件已保存在以下目录:\n"
    result_msg += "\n".join(output_dirs)
    
    if errors:
        result_msg += f"\n\n遇到{len(errors)}个错误:\n"
        result_msg += "\n".join(errors[:5])  # 只显示前5个错误
        if len(errors) > 5:
            result_msg += f"\n...以及{len(errors)-5}个其他错误"
    
    return result_msg

if __name__ == '__main__':
    # 需要转换的目录列表
    input_dirs = [
        r'J:\lqb\huanxingranliao\25CHJ02\Big F BiaoDing A\1000f4.7ms\C001H001S0001',
        r'J:\lqb\huanxingranliao\25CHJ02\Big F BiaoDing A\1000f0.1-5ms5-15-9\C001H001S0001',
        r'J:\lqb\huanxingranliao\25CHJ02\Big F BiaoDing A\1000f5-0.1ms5-15-9\C001H001S0001',
        r'J:\lqb\huanxingranliao\25CHJ02\Big F BiaoDing A\1000f4.7ms\C001H001S0001'
    ]
    
    result = convert_png_to_bmp(input_dirs)
    print(result)
